<template>
	<div class="data-summary-page">
		<van-sticky>
			<van-search v-model="form.searchText" show-action :readonly="searchReadonly" placeholder="请输入搜索关键词" @search="onInputSearch">
				<template #action>
					<van-icon name="https://wx.ksepia.com/profile/mini-image/search@3x.png" @click="openFilterPopup" />
				</template>
			</van-search>
			<van-tabs v-model:active="active" color="#049DFC" sticky @change="onTabChange">
				<van-tab
					v-for="item in actives"
					:key="item.title + (item.dataLabel || item.name || '')"
					:title="item.title"
					:name="item.title"
					:dataLabel="item.dataLabel"
					:dataCategory="item.dataCategory"
				>
				</van-tab>
			</van-tabs>
		</van-sticky>

		<div class="task-item-list">
			<van-empty v-if="rawList.length === 0 && !loading" description="暂无任务数据" />
			<div
				v-for="(item, idx) in rawList"
				:key="item.id || item.srcDataId || idx"
				:class="['task-item', { read: item.processStatus === '1' }]"
				@click="gotoListInfoPage(item)"
			>
				<div class="task-item-hd">
					<p class="item-paikou">{{ item.pollutionSourceName }}</p>
					<div class="tag-item-view">
						<span class="tag-rwlxmc">{{ item.dataLabel }}</span>
						<span v-for="dc in item.dataCategory" :key="dc" class="tag-rwlbmc" v-show="item.srcTableName !== 'v_biz_zczj_fac_check'">{{ dc }}</span>
					</div>
				</div>
				<div class="task-item-bd">
					<van-row>
						<van-col :span="6">
							<span class="item-pointer">
								<template v-if="item.srcTableName === 'biz_problem_rectify'">整改内容：</template>
								<template v-else-if="item.srcTableName === 'biz_report_things'">上报内容：</template>
								<template v-else-if="item.srcTableName === 'biz_facility_check_hhw'">贮存情况：</template>
								<template v-else-if="item.srcTableName === 'biz_facility_check_graywate'">说明：</template>
								<template v-else-if="item.srcTableName === 'v_biz_zczj_fac_check'">设施名称：</template>
								<template v-else>排口：</template>
							</span>
						</van-col>
						<van-col :span="18">
							<span class="task-item-ft-text value-text">{{ item.des || '' }}</span>
						</van-col>
					</van-row>
				</div>
				<div v-if="item.srcTableName === 'v_biz_zczj_fac_check'" class="task-item-bd">
					<van-row>
						<van-col :span="5"><span class="item-pointer">检查项：</span></van-col>
						<van-col :span="19"
							><span class="task-item-ft-text value-text-all">{{ item.ext1 || '' }}</span></van-col
						>
					</van-row>
				</div>
				<div v-if="item.srcTableName === 'v_biz_zczj_fac_check'" class="task-item-bd">
					<van-row>
						<van-col :span="5"><span class="item-pointer">检查结果：</span></van-col>
						<van-col :span="19"
							><span class="task-item-ft-text value-text">{{ item.ext2 || '' }}</span></van-col
						>
					</van-row>
				</div>
				<div v-if="item.fillUser" class="task-item-bd">
					<van-row>
						<van-col :span="12">
							<van-icon name="https://wx.ksepia.com/profile/mini-image/do-task-time-icon.png" size="12" />
							<span class="task-item-ft-text dead-time">{{ item.fillTime }}</span>
						</van-col>
						<van-col :span="12">
							<div class="item-distance">
								<van-icon name="https://wx.ksepia.com/profile/mini-image/do-task-user-icon@3x.png" size="12" />
								<div class="item-user">
									{{ item.fillUser }}
								</div>
							</div>
						</van-col>
					</van-row>
				</div>
			</div>
			<van-loading v-if="loading && rawList.length === 0" type="spinner" color="#049DFC" vertical>加载中...</van-loading>
			<van-divider v-if="rawList.length > 0 && rawList.length === total && hasScrolled && !loading" content-position="center">
				我也是有底线的
			</van-divider>
			<div v-if="rawList.length < total" class="load-more-wrap">
				<van-button size="small" type="primary" @click="loadMore" :loading="loading">加载更多</van-button>
			</div>
		</div>

		<van-popup v-model:show="showFilterPopup" position="right" :style="{ width: '80%', height: '100%' }" @click-overlay="closeFilterPopup">
			<div class="filter-popup">
				<van-cell-group>
					<FormPopupSelect
						required
						label="行政区划"
						field-key="areaCode"
						v-model:value="form.areaCode"
						dic-key="AREA_CODE"
						field="text"
						@popup-confirm="onPopupConfirmAreaCode"
					/>
					<van-cell title="开始时间" :value="form.startDate || '请选择'" is-link @click="openBeginDatePopup">
						<template #right-icon><van-icon name="clock" color="#969799" size="20" /></template>
					</van-cell>
					<van-cell title="结束时间" :value="form.endDate || '请选择'" is-link @click="openEndDatePopup">
						<template #right-icon><van-icon name="clock" color="#969799" size="20" /></template>
					</van-cell>
				</van-cell-group>
				<div class="bot-btn-wrap">
					<van-row :gutter="15">
						<van-col :span="12"><van-button block plain type="primary" @click="handleReset"> 重置 </van-button></van-col>
						<van-col :span="12"><van-button block type="primary" @click="handleSearch"> 搜索 </van-button></van-col>
					</van-row>
				</div>
			</div>
		</van-popup>

		<van-popup v-model:show="showDatePopup" position="bottom">
			<van-date-picker @cancel="closeDatePopup" @confirm="handleConfirmDate" title="选择年月日" />
		</van-popup>
		<van-popup v-model:show="showAreaPicker" position="bottom">
			<van-picker :columns="areaColumns" @cancel="showAreaPicker = false" @confirm="handleAreaConfirm" title="选择行政区划" />
		</van-popup>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { showToast } from 'vant'
import { TABS, EMPTY_FORM, ROUTER_MAP } from './constants'
import * as dataSummaryApi from '@/api/dataSummary'
import { useUserStore } from '@/stores/user'
import FormPopupSelect from '../../components/form-popup-select'
import router from '../../router'

export default {
	name: 'DataSummary',
	components: { FormPopupSelect },
	setup() {
		const route = useRoute()
		const userStore = useUserStore()

		const active = ref('')
		const actives = ref([])
		const form = reactive({ ...EMPTY_FORM })
		const rawList = ref([])
		const pageNum = ref(1)
		const pages = ref(0)
		const total = ref(0)
		const hasScrolled = ref(false)
		const loading = ref(false)
		const searchReadonly = ref(false)
		const showFilterPopup = ref(false)
		const showDatePopup = ref(false)
		const currOpenDate = ref('startDate')
		const showAreaPicker = ref(false)
		const currentDate = ref(new Date())

		const formatTime = (date) => {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		}

		const queryRawList = async () => {
			const filterForm = {
				...form,
				pageNum: pageNum.value,
				pageSize: 10,
			}
			loading.value = true
			try {
				const res = await dataSummaryApi.getDataSummaryList(filterForm)
				if (res.code === '0') {
					res.rows.forEach((c) => (c.dataCategory = c.dataCategory ? c.dataCategory.split(',') : []))
					const list = filterForm.pageNum === 1 ? [] : rawList.value
					rawList.value = list.concat(res.rows)
					pages.value = res.pages
					total.value = res.total
				} else {
					showToast(res.message || '获取数据失败')
				}
			} catch (e) {
				console.error('获取数据列表失败', e)
				showToast('网络错误，请稍后再试')
			} finally {
				loading.value = false
			}
		}
		const onTabChange = (e) => {
			const name = e
			const tabObj = actives.value.find((t) => t.title === name)
			const dataLabel = tabObj?.dataLabel
			const title = tabObj?.title
			console.log('切换tab', name, dataLabel)
			if (title === '全部') {
				form.dataLabel = ''
				form.dataCategory = ''
				handleReset(false)
				pageNum.value = 1
				rawList.value = []
				queryRawList()
				return
			}
			form.dataCategory = name
			if (dataLabel === '设施点检') {
				form.dataCategory = tabObj.dataCategory
				form.dataLabel = dataLabel
			} else {
				form.dataLabel = tabObj?.dataLabel
				form.dataCategory = ''
			}
			rawList.value = []
			pageNum.value = 1
			queryRawList()
		}

		const onInputSearch = (val) => {
			form.searchText = val
			pageNum.value = 1
			rawList.value = []
			queryRawList()
		}

		const openFilterPopup = () => {
			showFilterPopup.value = true
			searchReadonly.value = true
		}
		const closeFilterPopup = () => {
			showFilterPopup.value = false
			searchReadonly.value = false
		}

		const openBeginDatePopup = () => {
			currOpenDate.value = 'startDate'
			showDatePopup.value = true
		}
		const openEndDatePopup = () => {
			currOpenDate.value = 'endDate'
			showDatePopup.value = true
		}
		const closeDatePopup = () => {
			showDatePopup.value = false
		}
		const handleConfirmDate = ({ selectedValues }) => {
			const [y, m, d] = selectedValues
			const dateStr = `${y}-${m}-${d}`
			form[currOpenDate.value] = dateStr
			closeDatePopup()
		}

		const handleAreaConfirm = ({ selectedOptions }) => {
			const option = selectedOptions[0]
			form.areaCode = option.value
			form.areaName = option.text
			showAreaPicker.value = false
		}

		const handleReset = (refresh = true) => {
			const { dataLabel, dataCategory } = form
			Object.assign(form, { ...EMPTY_FORM })
			form.dataLabel = dataLabel
			form.dataCategory = dataCategory
			form.areaCode = ''
			if (refresh) {
				pageNum.value = 1
				rawList.value = []
				queryRawList()
			}
		}

		const handleSearch = () => {
			closeFilterPopup()
			pageNum.value = 1
			rawList.value = []
			queryRawList()
		}

		const gotoListInfoPage = (item) => {
			const routerConfig = ROUTER_MAP.find((d) => d.srcTableName === item.srcTableName)
			if (!routerConfig?.page) return
			let params = `?id=${item.srcDataId || item.id}&isView=true`
			if (item.srcTableName === 'v_biz_zczj_fac_check') {
				params = `?enterpriseId=${item.pollutionSourceId}&facilityId=${item.srcDataId || item.id}&finishedAt=${item.fillTime}&userId=${item.remark}`
			}
			const viewUrl = `${routerConfig.page}${params}`
			if (!item.srcDataId && !item.id) {
				showToast('记录缺少ID')
				return
			}
			console.log('跳转详情页', viewUrl)
			// use global router instance, because useRoute() returns current route object without navigation APIs
			router.push(viewUrl)
		}

		const initTabs = async () => {
			try {
				const user = await userStore.ensureLogin()
				if (user.userRoles !== 'government' && user.omDepts?.existSzesisc !== '1') {
					actives.value = TABS.filter((t) => t.dataLabel !== '自查自纠')
				} else {
					actives.value = [...TABS]
				}
				const { active: activeParam } = route.query
				if (activeParam) {
					active.value = activeParam
					form.dataLabel = activeParam
				} else {
					active.value = ''
				}
				queryRawList()
			} catch (e) {
				console.error('初始化失败', e)
			}
		}

		const loadMore = () => {
			const next = pageNum.value + 1
			if (next > pages.value) return
			pageNum.value = next
			hasScrolled.value = true
			queryRawList()
		}
		onMounted(() => {
			initTabs()
		})

		return {
			active,
			actives,
			form,
			rawList,
			loading,
			pageNum,
			pages,
			total,
			hasScrolled,
			searchReadonly,
			showFilterPopup,
			showDatePopup,
			showAreaPicker,
			openFilterPopup,
			closeFilterPopup,
			onTabChange,
			gotoListInfoPage,
			onInputSearch,
			openBeginDatePopup,
			openEndDatePopup,
			closeDatePopup,
			handleConfirmDate,
			handleReset,
			handleSearch,
			handleAreaConfirm,
			loadMore,
		}
	},
}
</script>

<style lang="less" scoped>
.data-summary-page {
	background-color: #f0f0f0;
	min-height: 100vh;

	:deep(.van-tabs__content) {
		padding: 0;
	}
}

.task-item-list {
	padding: 10px 16px;
	min-height: 100%;
	background: #f0f0f0;
}

.task-item {
	margin-bottom: 10px;
	border-radius: 3px;
	background: #fff;
	padding: 0 0 0 15px;
	cursor: pointer;
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
		background: #f8f8f8;
	}

	&.read {
		opacity: 0.7;
	}
}

.task-item-hd {
	padding: 10px 0;
	position: relative;

	.item-paikou {
		color: #333;
		font-weight: 600;
		margin: 0 0 8px 0;
	}
}

.tag-item-view {
	position: relative;

	.tag-rwlxmc {
		background-color: #f2f6ff;
		color: #625efd;
		font-size: 10px;
		font-weight: 600;
		padding: 2px 4px;
		margin-right: 10px;
		border-radius: 2px;
	}

	.tag-rwlbmc {
		background-color: #eefdf4;
		color: #31e087;
		font-size: 10px;
		font-weight: 600;
		padding: 2px 4px;
		margin-right: 10px;
		border-radius: 2px;
	}
}

.task-item-bd {
	padding: 0 10px 10px 0;

	.item-pointer {
		font-size: 14px;
		font-weight: 600;
		color: #202739;
	}
}

.task-item-ft-text {
	font-size: 12px;
	color: #333;
}
.value-text-all {
	font-size: 12px;
	color: #333;
}

.dead-time {
	margin-left: 4px;
}

.item-distance {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	.item-user {
		margin-left: 8px;
	}
}

.filter-popup {
	height: 100%;
	display: flex;
	flex-direction: column;

	.bot-btn-wrap {
		padding: 15px;
		margin-top: auto;
	}
}
.load-more-wrap {
	text-align: center;
	padding: 10px 0;
}
</style>
